/**
 * 
 */
package test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * 
 */
public class Printer {
    public static int[] printMatrix(int[][] mat, int n, int m) {
        // write code here
        int[] a = new int[n * m];
        int count = 0;
        for (int i = 0; i < mat.length; i++) {
            if (i % 2 == 0) {
                for (int j = 0; j < mat[i].length; j++) {
                    a[count++] = mat[i][j];
                }
            } else {
                for (int j = mat[i].length - 1; j >= 0; j--) {
                    a[count++] = mat[i][j];
                }
            }

        }

        return a;
    }

    public static void main(String[] args) {

        int[][] a = new int[5][3];
        a[0][0] = 1;
        a[0][1] = 2;
        a[0][2] = 3;
        a[1][0] = 4;
        a[1][1] = 5;
        a[1][2] = 6;
        a[2][0] = 7;
        a[2][1] = 8;
        a[2][2] = 9;
        a[3][0] = 10;
        a[3][1] = 11;
        a[3][2] = 12;
        a[4][0] = 13;
        a[4][1] = 14;
        a[4][2] = 15;

        // System.out.println(Arrays.toString(printMatrix(a, 4, 3)));

        System.out.println(Arrays.toString(clockwisePrint(a, 5, 3)));

    }

    public static int[] clockwisePrint(int[][] mat, int n, int m) {
        int a[] = new int[m * n];

        int hang = 0;
        int lie = 0;
        int arraycount = 0;
        int quancount = 0;

        Map<String, String> chenkKey = new HashMap<String, String>();

        while (!chenkKey.containsKey(hang + "," + lie)) {

            while (hang < n - quancount && lie < m - quancount) {
                chenkKey.put(hang + "," + lie, "");
                if (lie < m - quancount - 1)
                    a[arraycount++] = mat[hang][lie++];
                else
                    a[arraycount++] = mat[hang++][lie];
            }
            hang--;
            lie--;
            while (hang > quancount  || lie >  quancount) {
                chenkKey.put(hang + "," + lie, "");
                if (lie > quancount)
                    a[arraycount++] = mat[hang][lie--];
                else
                    a[arraycount++] = mat[hang--][lie];
            }
            quancount++;
            hang = quancount;
            lie = quancount;

        }
        return a;
    }
}
